const multer = require('multer');
const config = require('../config');
const iconvLite = require('iconv-lite');

const storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, config.fileSite);
    },
    filename(req, file, cb) {
        let math = Math.random().toString().replace(".", ""); // 随机字符串
        const decodedOriginalName = iconvLite.decode(Buffer.from(file.originalname, 'binary'), 'utf-8'); // 使用 iconv-lite 模块将乱码解码为 utf-8
        cb(null, `${Date.now()}${math}-${decodedOriginalName}`);
    }
});

const upload = multer({
    storage
}).array(config.fileName);

const fileEvent = (req, res) => {
    return new Promise((resolve, reject) => {
        upload(req, res, function (err) {
            if (err) {
                console.error(err);
                res.send({ code: 500, msg: '上传失败' });
                return;
            }
           
            try {
                const imgPath = req.files.map((i) => {
                    const fileUrl = `${config.fileHost}/${i.filename}`;
                    const decodedOriginalName = iconvLite.decode(Buffer.from(i.originalname, 'binary'), 'utf-8');
                    return {
                        fileUrl,
                        name: decodedOriginalName,
                        filename: i.filename
                    };
                });
                resolve(imgPath);
            } catch (err) {
                console.error(err);
                res.send({ code: 500, msg: '上传失败' });
            }
        });
    });
};

module.exports = fileEvent;